﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using FtpWorkerRole.FtpServer;
using FtpWorkerRole.AzureStorage;

namespace FtpWorkerRole.FtpCommand
{
    class RetrCommand : CommandBase
    {
        private const int bufferSize = 32768;
        public RetrCommand(FtpSocketHandler handler)
            : base(handler)
        {
            commandName = "RETR";
        }

        public override void execute(string value)
        {
            if (!handler.Login)
            {
                Utils.sendMessage(handler.getSocket(), formatMessage(530, "Please Login!"));
                return;
            }
            string path = "";
            string fileName = value;
            path = Path.Combine(handler.currentDirectory,fileName);

            if (!handler.fileSystem.isFileExist(path))
            {
                Utils.sendMessage(handler.getSocket(), formatMessage(550, string.Format("File {0} not exist!",path)));
                return;
            }

            Utils.sendMessage(handler.getSocket(), formatMessage(150, "Openning Channel Socket"));
            DataSocketHandler dataHandler = new DataSocketHandler(handler);
            if (dataHandler.open())
            {
                var file = handler.fileSystem.openFile(path,true);
                if (file == null)
                {
                    Utils.sendMessage(handler.getSocket(), formatMessage(550, "Cannot open file!"));
                    return;
                }
                file.File.Seek(0, System.IO.SeekOrigin.Begin);
                byte[] data = new byte[bufferSize];
                int nread = file.Read(data);
                while (nread > 0)
                {
                    dataHandler.sendData(data,nread);
                    nread = file.Read(data);
                }
                dataHandler.close();
                file.Close();
                Utils.sendMessage(handler.getSocket(), formatMessage(226, "Transfer Complete"));
            }
            else
            {
            }
        }
    }
}
